package org.dromara.system.utils;

import com.wechat.pay.java.core.Config;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.core.notification.NotificationConfig;
import com.wechat.pay.java.core.notification.NotificationParser;
import com.wechat.pay.java.core.notification.RequestParam;
import com.wechat.pay.java.service.payments.jsapi.JsapiService;
import com.wechat.pay.java.service.payments.jsapi.JsapiServiceExtension;
import com.wechat.pay.java.service.payments.jsapi.model.*;
import com.wechat.pay.java.service.payments.model.Transaction;
import org.dromara.system.domain.bo.ZtUserVipOrderBo;
import org.springframework.http.HttpHeaders;
import java.security.GeneralSecurityException;

public class QuickStart {
    /** 商户号 */
    public static String merchantId = "1676804649";
    /** 商户API私钥路径 */
    public static String privateKeyPath = "/WeChatCertificate/apiclient_key.pem";
    /** 商户证书序列号 */
    public static String merchantSerialNumber = "5361C428E0EF59454957FB6B26AB396E2793F41D";
    /** 商户APIV3密钥 */
    public static String apiV3Key = "Dfio3376Dfio3376Dfio3376Dfio3376";
    /** 支付通知URL */
    public static String notifyUrl = "http://5mieyy.natappfree.cc/xcx/user/vip/wx/notify_url";

    private static Config config;

    private static void setConfig(){
        if(config == null){
            config = new RSAAutoCertificateConfig.Builder()
                    .merchantId(merchantId)
                    .privateKeyFromPath(privateKeyPath)
                    .merchantSerialNumber(merchantSerialNumber)
                    .apiV3Key(apiV3Key)
                    .build();
        }
    }

    /**
     * 用户下单
     * @param bo
     */
    public static PrepayWithRequestPaymentResponse userPlacesAnOrder(ZtUserVipOrderBo bo){
        // 使用自动更新平台证书的RSA配置
        setConfig();
        JsapiServiceExtension service_sin = new JsapiServiceExtension.Builder().config(config).build();
        JsapiService service = new JsapiService.Builder().config(config).build();
        // request.setXxx(val)设置所需参数，具体参数可见Request定义
        PrepayRequest request = new PrepayRequest();
        Amount amount = new Amount();
        amount.setTotal(bo.getAmountTotal().intValue());
        request.setAmount(amount);
        request.setAppid(bo.getAppid());
        request.setMchid(merchantId);
        bo.setMchid(merchantId);
        request.setDescription(bo.getDescription());
        request.setNotifyUrl(notifyUrl);
        request.setOutTradeNo(bo.getOutTradeNo());
        Payer payer = new Payer();
        payer.setOpenid(bo.getOpenid());
        request.setPayer(payer);
        PrepayResponse response = service.prepay(request);
        bo.setPrepayId(response.getPrepayId());
        return service_sin.prepayWithRequestPayment(request);
    }

    /**
     * AEAD_AES_256_GCM 解密
     * @param headers
     * @param body
     * @return
     * @throws GeneralSecurityException
     */
    public static Transaction decrypt(HttpHeaders headers, String body)  {
        // 构造 RequestParam
        RequestParam requestParam = new RequestParam.Builder()
            .serialNumber(headers.getFirst("Wechatpay-Serial"))
            .nonce(headers.getFirst("Wechatpay-Nonce"))
            .signature(headers.getFirst("Wechatpay-Signature"))
            .timestamp(headers.getFirst("Wechatpay-Timestamp"))
            .body(body)
            .build();
//         初始化 NotificationParser
        NotificationParser parser = new NotificationParser((NotificationConfig) config);
        try {
            // 以支付通知回调为例，验签、解密并转换成 Transaction
            return parser.parse(requestParam, Transaction.class);
        } catch (Exception e) {
            return null;
        }
    }

}
